package com.hl.card.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hl.card.common.persistence.model.Recharge;
import com.hl.card.common.remote.resolve.RemoteService;
import com.hl.card.common.remote.user.RemoteUser;
import com.hl.card.modular.pack.service.RechargeService;
import com.hl.card.pay.dto.CollectDto;
import com.hl.card.pay.dto.RechargeDto;
import com.hl.card.pay.service.CollectService;
import com.hl.card.pay.util.PayDigestUtil;
import com.hl.card.pay.vo.CollectVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Date;

import static com.hl.card.pay.util.HttpTool.postJSONObject;

@Service
public class CollectServiceImpl implements CollectService {

    @Value("${pay.config.cardUrl}")
    private String cardUrl;

    @Value("${pay.config.mchInfo}")
    private String mchInfo;

    @Value("${pay.config.payChanel}")
    private String payChanel;

    @Value("${pay.config.reqKey}")
    private String reqKey;

    @Value("${pay.config.trade}")
    private String trade;

    @Value("${pay.config.cardBlance}")
    private String cardBalance;

    @Value("${pay.config.doTrans}")
    private String doTrans;

    @Value("${pay.config.mchId}")
    private String mchId;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RemoteService remoteService;

    @Override
    public String doCollect(CollectVo vo) {
        String amount=vo.getAmount();
        String orderNo="WITHDRAW"+System.currentTimeMillis()+"";
        Recharge recharge=new Recharge();
        recharge.setRecharge_no(orderNo);
        recharge.setExtra("WITHDRAW");
        recharge.setUser_id(vo.getUserId());
        recharge.setStatus(1);
        recharge.setAdd_time(new Date());
        recharge.setRecharge_no(orderNo);
        recharge.setRemarkInfo(vo.getRemarkInfo());
        recharge.setAmount(Double.parseDouble(amount+""));
        recharge.setCurrency(vo.getCurrency());
        recharge.setPoundage(Double.parseDouble(vo.getParam1()));//手续费
        RemoteUser remoteUser = remoteService.findUserById(recharge.getUser_id());
        //TODO  确定用户中心的数据可以取到
        if(null!=remoteUser){
            recharge.setBinding_phone(remoteUser.getMobilePhone());
            recharge.setFull_name(remoteUser.getUserName());
        }
        CollectDto  collectDto=new CollectDto();
        BeanUtils.copyProperties(vo,collectDto);
        collectDto.setChannelUser(vo.getUserId());
        collectDto.setMchId(mchId);
        collectDto.setMchTransNo(orderNo);
        collectDto.setAction("WITHDRAW");
        collectDto.setRemarkInfo("数字币提取");
        collectDto.setAmount(amount);
        collectDto.setParam1(vo.getParam1());
        collectDto.setSubject("提现");
        collectDto.setBody("提取数字币");
        collectDto.setClientIp("211.94.116.218");

        JSONObject paramMap= (JSONObject) JSON.toJSON(collectDto);
        String reqSign = PayDigestUtil.getSign(paramMap, reqKey);//请求参数签名
        String url = cardUrl+trade;
        JSONObject postData =(JSONObject) JSON.toJSON(collectDto);
        postData.put("sign",reqSign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        System.out.println(postData.toJSONString());
        map.add("params",postData.toJSONString());
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        String str = restTemplate.postForEntity(url, request, String.class).getBody();
        JSONObject strObj = JSONObject.parseObject(str);
        if(strObj.get("resCode").equals("SUCCESS")){
            recharge.insert();
        }

        return str;
    }
    /**
     * 获取可用余额
     * @param userId
     * @param currency
     * @return
     */
    @Override
    public Integer getBalance(String userId, String currency) {
        String url=cardUrl+cardBalance;
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("userId",userId);
        jsonObject.put("cardType",currency);
        JSONObject result = postJSONObject(url, jsonObject, restTemplate);
        if(result.get("code").equals(0)){
            JSONObject obj=  JSONObject.parseObject(result.get("obj").toString());
           Integer balance=  Integer.parseInt(obj.get("remainPart").toString());
           return  (balance-2)/100*100;
    }
        return 0;
    }

    /**
     * 获取全部余额
     * @param userId
     * @param currency
     * @return
     */
    @Override
    public Integer getBalanceAll(String userId, String currency) {
        String url=cardUrl+cardBalance;
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("userId",userId);
        jsonObject.put("cardType",currency);
        JSONObject result = postJSONObject(url, jsonObject, restTemplate);
        if(result.get("code").equals(0)){
            JSONObject obj=  JSONObject.parseObject(result.get("obj").toString());
            Integer balance=  Integer.parseInt(obj.get("remainPart").toString());
            return  balance;
        }
        return 0;
    }

    public JSONObject doTrans(CollectDto collectDto){
        String url = cardUrl+doTrans;
        String mchTransNo=collectDto.getMchTransNo();
        JSONObject paramMap = new  JSONObject();
        paramMap.put("mchTransNo", mchTransNo);
        paramMap.put("mchId", mchId);
//        Recharge rechage = rechargeService.selectById(mchTransNo);
        RechargeDto rechargeDto=new RechargeDto();
        rechargeDto.setChannelUser(collectDto.getChannelUser());
        rechargeDto.setMchId(mchId);
        rechargeDto.setMchTransNo(mchTransNo);
        rechargeDto.setAction("WITHDRAW");
        rechargeDto.setRemarkInfo("数字币充值");
        //todo 这里要考虑一下 是进行4舍5入 还是去掉小数点后面的
        rechargeDto.setAmount(collectDto.getAmount());
        rechargeDto.setParam1("0");
        rechargeDto.setSubject("TB");
        rechargeDto.setBody("数字币充值");
        rechargeDto.setClientIp("211.94.116.218");
        rechargeDto.setCurrency(collectDto.getCurrency());
        paramMap= (JSONObject) JSON.toJSON(rechargeDto);
        //商户信息
        //商户的reqkey
        String reqSign = PayDigestUtil.getSign(paramMap, reqKey);
        paramMap.put("sign", reqSign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        System.out.println(paramMap.toJSONString());
        map.add("params",paramMap.toJSONString());
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        String str = restTemplate.postForEntity(url, request, String.class).getBody();
        return JSONObject.parseObject(str);
    }
}
